import axios from 'axios'
import md5 from 'js-md5'
import CryptoJS from 'crypto-js'

const confige = {
  api_key: 'fag51sd5r8eF8A1Vds',
  code: '1635230227540WZH'
}

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_URL,
  timeout: 6000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error: any) => {
  // if (error.response) {
  //   const data = error.response.data || ''

  //   if (error.response.status !== 200) {

  //   }
  // }
  console.log('s', error)
  return Promise.reject(error)
}

const secretFn = (string: string, code: string, operation?: boolean) => {
  const key = CryptoJS.enc.Utf8.parse(code)
  if (operation) {
    // 解密
    const res = CryptoJS.AES.decrypt(string, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString(CryptoJS.enc.Utf8)
    try {
      return res.match(/\.(jpeg|jpg|gif|png)$/i) != null ? res : JSON.parse(res)
    } catch (e) {
      return res
    }
  } else {
    string = JSON.stringify(string)
    // 加密
    return CryptoJS.AES.encrypt(string, key, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    }).toString()
  }
}

// data加密
const signFn = (data: any) => {
  if (data == {} || data == [] || data == '' || data == null) data = {}
  data.version = 'v1'
  data.timestamp = Math.floor(new Date().getTime() / 1000)
  const array = Object.assign({ api_key: confige.api_key }, data)
  const keyarray = Object.keys(array).sort()
  let temp = ''
  for (const k in keyarray) {
    temp += (temp ? '&' : '') + keyarray[k] + '=' + array[keyarray[k]]
  }
  data.sign = md5(temp)
  return data
}

// 请求拦截
request.interceptors.request.use((config: any) => {
  config.headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: 'Bearer ' + localStorage.getItem('userToken') || '',
    lang: ''
  }
  config.data = signFn(config.data) || {}
  if (confige.code) {
    config.data = { data: secretFn(config.data, confige.code) }
  }
  return config
}, errorHandler)

// 响应拦截
request.interceptors.response.use((response) => {
  if (response.status == 200) {
    const result = response.data
    if (result !== '' && result.data != null && result.data != '') {
      result.data = secretFn(result.data, confige.code, true)
    }
    if (result.code && result.code !== 0) {
      return false
    }
  }
  return response.data
}, errorHandler)

export default request
